package com.zx.idc.backend.gui.shiro;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.zx.idc.backend.gui.common.Result;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 扩展shiro的Authentication filter，用以兼容验证码功能
 * @auth jinyuanf
 * @date 2019/4/28 11:45
 **/
@Service
public class SysFormAuthenticationFilter extends FormAuthenticationFilter {

    private static final Logger LOG = LoggerFactory.getLogger(SysFormAuthenticationFilter.class);
    private static final ObjectMapper MAPPER = new ObjectMapper();


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                //allow them to see the login page ;)
                return true;
            }
        } else {
            if(isAjaxRequest(req)){
                Result result = new Result<>(Result.UN_AUTHENTICATION, "您还未登录!", null);
                String json = MAPPER.writeValueAsString(result);
                writeJson(json,res);
            }
            else{
                saveRequestAndRedirectToLogin(request, response);
            }
            return false;
        }
    }


    /**
     *   是否是Ajax请求
     * @Description:
     * @param
     * @return
     * @throws
     * @author pengbin <pengbin>
     * 2018/11/26 10:58
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *   输出JSON
     * @Description:
     * @param
     * @return
     * @throws
     * @author pengbin <pengbin>
     * 2018/11/26 10:59
     */
    private void writeJson(String json, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            out.write(json);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }




}
